import { Applet } from "@/api/interface/iot";
import { addAppletPort, delAppletPort, getAppletPortList, modAppletPort } from "@/api/modules/applet/appletPort";
import DialogBox from "@/components/DialogBox";
import Empty from "@/components/Empty";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps } from "@/components/ProTable/interface";
import PublicTag from "@/components/Sansan/Status/PublicTag";
import { MessageType } from "@/enums/messageEnum";
import mittBus from "@/utils/mittBus";
import { confirm, showMsg, showTips } from "@/utils/util";
import { ElForm } from "element-plus";
import { ComponentInternalInstance, getCurrentInstance, PropType } from "vue";
import "../detail.scss";

export default defineComponent({
	props: {
		btns: {
			type: Array,
			default() {
				return [];
			}
		},
		nodeSn: String,
		detail: {
			type: Object as PropType<Applet.ResUserApplet>,
			default: () => {}
		}
	},
	emits: ["change"],
	setup(props) {
		const { proxy } = getCurrentInstance() as ComponentInternalInstance;
		// 表格配置项
		let columns = reactive<ColumnProps[]>([
			{ prop: "port", label: proxy?.$t("servicedialog.tablist_label.port") },
			{ prop: "proto", label: proxy?.$t("servicedialog.tablist_label.proto"), width: 120 },
			{ prop: "public", label: proxy?.$t("servicedialog.tablist_label.public") },
			{ prop: "desc", label: proxy?.$t("servicedialog.tablist_label.desc") },
			{ prop: "op", label: proxy?.$t("servicedialog.tablist_label.op"), width: 130 }
		]);
		// const btnList = ref([{ menuName: "添加端口", path: "add", btnClass: "primary" }]);
		const btnList = ref<any[]>([]);
		watchEffect(() => {
			btnList.value = (props.btns || []).filter((item: any) => item.btnGroup == "4");
			columns = columns.map((item: any) => {
				if (item.prop == "op") {
					item.isShow = !!btnList.value.length;
				}
				return item;
			});
		});
		const initParam = reactive({ appId: props.detail.id, nodeSn: props.nodeSn, pageSize: 5 });
		const proTable = ref();
		const dataCallback = (data: any) => {
			return {
				datalist: data.records,
				total: data.total || 0,
				pageIndex: data.current,
				pageSize: data.size
			};
		};

		type FormInstance = InstanceType<typeof ElForm>;
		const formRef = ref<FormInstance>();
		const formRule = reactive({
			port: [{ required: true, message: proxy?.$t("servicedialog.form_rule.port"), trigger: "change" }],
			proto: [{ required: true, message: proxy?.$t("servicedialog.form_rule.proto"), trigger: "change" }]
		});

		const clickBtn = (fn: string, row?: any) => {
			let selected = row ? (row.selectList ? row.selectList : [row]) : [];
			console.log(row);
			switch (fn) {
				case "add":
					detailDialog.visible = true;
					detailDialog.detail = { id: "", appId: props.detail.id, port: "", public: "yes", proto: "tcp", desc: "" };
					break;
				case "mod":
					detailDialog.visible = true;
					detailDialog.detail = { ...row };
					break;
				case "del":
					if (!selected.length) {
						showMsg(proxy?.$t("servicedialog.msg.del"), MessageType.warning);
						return;
					}
					confirm({ content: proxy?.$t("servicedialog.confirm.del") }).then(flag => {
						flag && submitDel({ id: selected.map((item: any) => item.id).join(",") });
					});
					break;
			}
		};
		const detailDialog = reactive({
			visible: false,
			title: proxy?.$t("servicedialog.dialog_title.port"),
			detail: { id: "", appId: "", port: "", public: "", proto: "", desc: "" }
		});
		const submit = async () => {
			let api = detailDialog.detail.id ? modAppletPort : addAppletPort;
			let res = await api(detailDialog.detail);
			let ok = showTips(res.code, detailDialog.detail.id ? "修改端口" : "添加端口", res.message);
			if (ok) {
				proTable.value.reset();
			}
			detailDialog.visible = false;
		};
		const submitDel = async (dataInfo: any) => {
			let res = await delAppletPort({ ...dataInfo });
			let ok = showTips(res.code, "删除", res.message);
			if (ok) {
				proTable.value.clearSelection();
				proTable.value.reset();
			}
		};
		onBeforeMount(() => {
			mittBus.on("refreshAppletDetail", () => {
				proTable.value.reset();
			});
		});
		onBeforeUnmount(() => {
			mittBus.off("refreshAppletDetail");
		});
		return () => {
			return (
				<div class="p-6 shadow mt-4" style="border: 1px solid #eee;">
					<DialogBox v-model:visible={detailDialog.visible} title={detailDialog.title} width="650px" onConfirm={() => submit()}>
						<el-form model={detailDialog.detail} ref={formRef} rules={formRule} label-width="100px" class="pl-4 pr-10">
							<el-form-item label={proxy?.$t("servicedialog.form_label.port")} prop="port">
								<el-input
									v-model={detailDialog.detail.port}
									placeholder={proxy?.$t("servicedialog.placeholder.port")}
									type="number"
								/>
							</el-form-item>
							<el-form-item label={proxy?.$t("servicedialog.form_label.proto")} prop="proto">
								<el-select v-model={detailDialog.detail.proto} clearable allow-create filterable default-first-option>
									<el-option value="http" label="http" />
									<el-option value="mqtt" label="mqtt" />
									<el-option value="tcp" label="tcp" />
									<el-option value="udp" label="udp" />
								</el-select>
							</el-form-item>
							<el-form-item label={proxy?.$t("servicedialog.form_label.public")} prop="public">
								<el-select v-model={detailDialog.detail.public}>
									<el-option value="yes" label={proxy?.$t("servicedialog.option.yes")} />
									<el-option value="no" label={proxy?.$t("servicedialog.option.no")} />
								</el-select>
							</el-form-item>
							<el-form-item label={proxy?.$t("servicedialog.form_label.desc")} prop="desc">
								<el-input
									v-model={detailDialog.detail.desc}
									placeholder={proxy?.$t("servicedialog.placeholder.desc")}
									auto-size
									type="textarea"
									rows={4}
								/>
							</el-form-item>
						</el-form>
					</DialogBox>
					<div class="flex items-center justify-between w-full pb-4">
						<div style="line-height:24px">
							<div class="title-left-line"></div>
							<span>{proxy?.$t("servicedialog.tab_title.port")}</span>
						</div>
						<div class="">
							{btnList.value
								?.filter((item: any) => item.path != "del")
								.map((item: any) => {
									return (
										<el-button onClick={() => clickBtn(item.path)} type={item.btnClass}>
											<i class={`iconfont ${item.icon}`}></i>
											{item.menuName}
										</el-button>
									);
								})}
						</div>
					</div>
					<ProTable
						ref={proTable}
						custSearch={false}
						showHeader={false}
						title={proxy?.$t("servicedialog.tab_title.port")}
						columns={columns}
						requestApi={getAppletPortList}
						initParam={initParam}
						dataCallback={dataCallback}
					>
						{{
							public: (scope: any) => {
								return (
									<PublicTag
										v-model={scope.row.public}
										types={{ yes: "success", no: "danger" }}
										labels={{ yes: proxy?.$t("servicedialog.option.yes"), no: proxy?.$t("servicedialog.option.no") }}
									/>
								);
							},
							op: (scope: any) => {
								return (
									<>
										<el-link
											type="danger"
											link
											class="iconfont icontrash-2"
											onClick={() => {
												clickBtn("del", scope.row);
											}}
										>
											{proxy?.$t("servicedialog.link.delete")}
										</el-link>
										<el-link
											type="primary"
											link
											class="iconfont iconbx-file"
											onClick={() => {
												clickBtn("mod", scope.row);
											}}
										>
											{proxy?.$t("servicedialog.link.detail")}
										</el-link>
									</>
								);
							},
							empty: () => {
								return (
									<div class="">
										<Empty
											onAdd={() => {
												clickBtn("add");
											}}
											showButton={false}
											title={proxy?.$t("servicedialog.empty.title")}
											subtitle={proxy?.$t("servicedialog.empty.subtitle")}
										/>
									</div>
								);
							}
						}}
					</ProTable>
				</div>
			);
		};
	}
});
